package com.example.springboottestgit.service;

import com.example.springboottestgit.bean.BusinessException;
import com.example.springboottestgit.bean.CommonException;
import com.example.springboottestgit.bean.InviteTenderFileUploadRecord;
import com.example.springboottestgit.bean.SubmitTenderFileUploadRecord;
import com.example.springboottestgit.bean.vo.InviteTenderFileVO;
import com.example.springboottestgit.bean.vo.SubmitTenderFileVO;
import com.example.springboottestgit.dao.InviteTenderFileUploadRecordMapper;
import com.example.springboottestgit.dao.SubmitTenderFileUploadRecordMapper;
import com.example.springboottestgit.enums.ExceptionCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @description:
 * @author: ZZZ
 */
@Slf4j
@Service
public class FileService {
    @Value("${invite.tender.upload.path}")
    private String inviteTenderUploadPath;

    @Value("${submit.tender.upload.path}")
    private String submitTenderUploadPath;

    @Autowired
    private InviteTenderFileUploadRecordMapper inviteTenderFileUploadRecordMapper;
    @Autowired
    private SubmitTenderFileUploadRecordMapper submitTenderFileUploadRecordMapper;

    @Autowired
    private ExeScriptServer exe;

    public InviteTenderFileVO inviteTenderUpload(MultipartFile multipartFile, String bsn, int fileType) {
        InviteTenderFileVO vo = new InviteTenderFileVO();

        // 获取文件名 xxx.doc
        String sourceFileName = multipartFile.getOriginalFilename().replace(" ", "");
        // xxx
        String prefixName = sourceFileName.substring(0, sourceFileName.lastIndexOf("."));
        // 获取文件的后缀名  .doc
        String suffixName = sourceFileName.substring(sourceFileName.lastIndexOf("."));
        // 上传后的路径
        //String filePath = inviteTenderUploadPath;
        String filePath = inviteTenderUploadPath + bsn + "/招标/" + sourceFileName;

        //fileName = UUID.randomUUID() + suffixName;
        //long timestamp = System.currentTimeMillis();

        //String uuid = String.valueOf(UUID.randomUUID()).replace("-", "");

        //String newFileNameAll = prefixName + "-" + uuid + suffixName;
        //String newFileName = prefixName + "-" + uuid;

        // 构建上传路径
        File dest = new File(filePath);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        InviteTenderFileUploadRecord insert = new InviteTenderFileUploadRecord();
        try {
            // 保存文件
            log.info("========招标文件上传==========");
            multipartFile.transferTo(dest);
            insert.setFileName(sourceFileName);
            insert.setSourceFileName(sourceFileName);
            insert.setFilePath(filePath);
            insert.setStatus(0);
            insert.setBsn(bsn);
            insert.setFileType(fileType);
            //insert.setInviteTenderTxtPath(tenderAnalysisPath + bsn + "-招标");
            inviteTenderFileUploadRecordMapper.insert(insert);
            BeanUtils.copyProperties(insert, vo);

            //执行解析脚本
//            log.info("========开始调用招投标解析接口==========");
//            String exeResult = exe.exeScript(filePath + newFileNameAll, newFileName, 1);
//            if ("0".equals(exeResult)) {
//                log.error("招标文件解析失败");
//                throw new BusinessException(ExceptionCodeEnum.BUSINESS_ERROR.code, "招标文件解析失败");
//            }

        } catch (Exception e) {
            if (insert.getId() != null) {
                insert.setStatus(2);
                inviteTenderFileUploadRecordMapper.updateById(insert);
            }
            if (e instanceof CommonException) {
                CommonException commonException = (CommonException) e;
                throw commonException;
            }
            log.error("招标文件上传失败", e);
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_ERROR.code, "招标文件上传失败");
        }
        return vo;
    }


    public SubmitTenderFileVO submitTenderUpload(MultipartFile multipartFile, String bsn, int fileType) {

//        InviteTenderFileUploadRecord inviteTenderFileUploadRecord = inviteTenderFileUploadRecordMapper.selectById(inviteTenderFileId);
//        if (inviteTenderFileUploadRecord == null) {
//            throw new CommonException("001001", "投标文件不存在");
//        }
//        if (inviteTenderFileUploadRecord.getStatus() != 1) {
//            throw new CommonException("001001", "投标文件上传失败");
//        }
//        String inviteTenderTxtPath = tenderAnalysisPath + inviteTenderFileUploadRecord.getFileName();


        SubmitTenderFileVO vo = new SubmitTenderFileVO();
        // 获取文件名 xxx.doc
        String sourceFileName = multipartFile.getOriginalFilename().replace(" ", "");
        // xxx
        String prefixName = sourceFileName.substring(0, sourceFileName.lastIndexOf("."));
        // 获取文件的后缀名  .doc
        String suffixName = sourceFileName.substring(sourceFileName.lastIndexOf("."));
        // 上传后的路径
        //String filePath = submitTenderUploadPath;
        String filePath = submitTenderUploadPath + bsn + "/投标/" + sourceFileName;

        //fileName = UUID.randomUUID() + suffixName;
        //String uuid = String.valueOf(UUID.randomUUID()).replace("-", "");

        //String newFileNameAll = prefixName + "-" + uuid + suffixName;
        //String newFileName = prefixName + "-" + uuid;

        // 构建上传路径
        File dest = new File(filePath);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        SubmitTenderFileUploadRecord insert = new SubmitTenderFileUploadRecord();
        try {

            // 保存文件
            log.info("========投标文件上传==========");
            multipartFile.transferTo(dest);
            //insert.setInviteTenderFileId(inviteTenderFileId);
            insert.setBsn(bsn);
            insert.setFileType(fileType);
            insert.setFileName(sourceFileName);
            insert.setSourceFileName(sourceFileName);
            insert.setFilePath(filePath);
            insert.setStatus(0);
            //insert.setSubmitTenderTxtPath(tenderAnalysisPath + bsn + "-投标");
            submitTenderFileUploadRecordMapper.insert(insert);
            BeanUtils.copyProperties(insert, vo);

            //String exeFilepath = filePath + newFileNameAll;
            //String exeFileName = newFileName;

            //String submitTenderTxtPath = tenderAnalysisPath + newFileName;
            //submitTenderService.submitTenderContentQa(submitTenderTxtPath, inviteTenderTxtPath, insert.getId(), inviteTenderFileId, exeFilepath, exeFileName);
        } catch (Exception e) {
            if (insert.getId() != null) {
                insert.setStatus(2);
                submitTenderFileUploadRecordMapper.updateById(insert);
            }

            if (e instanceof CommonException) {
                CommonException commonException = (CommonException) e;
                throw commonException;
            }
            log.error("投标文件上传失败", e);
            //submitTenderService.updateStatus(id, id2, 2);
            //throw new BusinessException("001001", "投标文件上传失败: " + e.getMessage());
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_ERROR.code, "投标文件上传失败");
        }
        return vo;
    }

}

